#!/usr/bin/python
# -*- coding: utf-8 -*-
#"""
#|===== Conference Bot Plugin ============
#|= Information Commands
#|===== By: ==============================
#|= Patrick Kennedy
#|===== Current Version: =================
#|= 1.0
#|===== Description: =========================================
#|= Various commands designed to display information about the bot.
#|===== Additional Comments: =================================
#|=
#|============================================================"""
import time
from xml.dom import minidom
from urllib import urlencode
import urllib, urllib2

def init(bot):
	bot.addCommand("погода", cmd_weather)
	bot.addCommand("прогноз",cmd_forecast)

def unload(bot):
	bot.removeCommand(["погода"], ["прогноз"])

def useragent():
	""" provide useragent string """
	return 'Mozilla/5.0 (compatible; Bot v0.1; )'


class CBURLopener(urllib.FancyURLopener):

	""" our URLOpener """

	def __init__(self, version, *args):
		if version:
			self.version = version
		else:
			self.version = useragent()
		urllib.FancyURLopener.__init__(self, *args)


def geturl(url, version=None):
	""" fetch an url """
	urllib._urlopener = CBURLopener(version)
	#rlog(5, 'generic', 'fetching %s' % url)
	result = urllib.urlopen(url)
	tmp = result.read()
	result.close()
	return tmp

def cmd_weather(bot,user,args):
	"""Показывает текущую погоду.
Использование: !погода <город>"""

	if not args:
		bot.msg(user,cmd_weather.__doc__)
		return

	loc = args
	query = urlencode({'weather':loc})
	weathertxt = geturl('http://www.google.ru/ig/api?%s' % query)
	resultstr = ""

	if len(weathertxt) > 135:
		gweather = minidom.parseString(weathertxt)
		gweather = gweather.getElementsByTagName('weather')[0]
		info = gweather.getElementsByTagName('forecast_information')[0]
		city = info.getElementsByTagName('city')[0].attributes["data"].value
		zip = info.getElementsByTagName('postal_code')[0].attributes["data"].value
		time = info.getElementsByTagName('current_date_time')[0].attributes["data"].value

		weather = gweather.getElementsByTagName('current_conditions')[0]
		condition = weather.getElementsByTagName('condition')[0].attributes["data"].value
		temp_f = weather.getElementsByTagName('temp_f')[0].attributes["data"].value
		temp_c = weather.getElementsByTagName('temp_c')[0].attributes["data"].value
		humidity = weather.getElementsByTagName('humidity')[0].attributes["data"].value
		wind = weather.getElementsByTagName('wind_condition')[0].attributes["data"].value

		#city = loc
		try:
			wind_km = round(int(wind[-6:-4]) * 1.609344)
		except ValueError:
			wind_km = ""

		if (not condition == ""):
			#condition = " Oh, and it's " + condition + "."
			condition = condition.lower()
			condition = " Да и кстати, там *" + unicode(condition).encode('utf-8') + "*."

		time = unicode(time).encode('utf-8')
		city = unicode(city).encode('utf-8')
		temp_c = unicode(temp_c).encode('utf-8')
		humidity = unicode(humidity).encode('utf-8')
		wind = unicode(wind).encode('utf-8')
		wind_km = unicode(wind_km).encode('utf-8')
		#condition = unicode(condition).encode('utf-8')
		#resultstr = "As of %s, %s (%s) has a temperature of %sC/%sF with %s. %s (%s km/h).%s" % (time, city, zip, temp_c, temp_f, humidity, wind, wind_km, condition)
		resultstr = "Погода на %s, %s. *Температура*: %s по цельсию  %s. %s.%s" % (time, city, temp_c, humidity, wind, condition)
	if not resultstr:
		bot.msg(user,'Город %s не найден!' % loc)
		return
	else:
		bot.msg(user,resultstr)

def cmd_forecast(bot,user,args):
	"""Показывает прогноз погоды на 3 дня.
Использование: !прогноз <город>"""

	if not args:
		bot.msg(user,cmd_forecast.__doc__)
		return

	loc = args
	query = urlencode({'weather':loc})
	weathertxt = geturl('http://www.google.ru/ig/api?%s' % query)
	resultstr = ""

	if len(weathertxt) > 135:
		gweather = minidom.parseString(weathertxt)
		gweather = gweather.getElementsByTagName('weather')[0]
		forecasts = gweather.getElementsByTagName('forecast_conditions')
		for forecast in forecasts:
			condition = forecast.getElementsByTagName('condition')[0].attributes["data"].value
			low_f = forecast.getElementsByTagName('low')[0].attributes["data"].value
			high_f = forecast.getElementsByTagName('high')[0].attributes["data"].value
			day = forecast.getElementsByTagName('day_of_week')[0].attributes["data"].value
			low_c = round((int(low_f) - 32) * 5.0 / 9.0)
			high_c = round((int(high_f) - 32) * 5.0 / 9.0)
			resultstr += "[%s: %s..%s C, %s]\n" % (day, low_f, high_f, condition)
	if not resultstr:
		bot.msg(user,'Город %s не найден!' % loc)
		return
	else:
		bot.msg(user,resultstr)


